package cn.iocoder.yudao.module.mqtt.controller.admin.mqtt;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.mqtt.controller.admin.config.vo.ConfigPageReqVO;
import cn.iocoder.yudao.module.mqtt.controller.admin.config.vo.ConfigRespVO;
import cn.iocoder.yudao.module.mqtt.dal.dataobject.config.MqttConfig2DO;
import cn.iocoder.yudao.module.mqtt.dal.dataobject.mqtt.MqttConfigDO;
import cn.iocoder.yudao.module.mqtt.framework.mqtt.MqttInstanceManager;
import cn.iocoder.yudao.module.mqtt.service.mqtt.MqttConfigService;
import cn.iocoder.yudao.module.mqtt.service.mqtt.MqttConnectionMonitorService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * MQTT配置管理 Controller
 *
 * @author 芋道源码
 */
@Tag(name = "管理后台 - MQTT配置管理")
@RestController
@RequestMapping("/mqtt/configServer")
@Validated
public class MqttConfigController {

    @Autowired
    private MqttConfigService mqttConfigService;

    @Autowired
    private MqttInstanceManager mqttInstanceManager;

    @Autowired
    private MqttConnectionMonitorService mqttConnectionMonitorService;

    @GetMapping("/page")
    @Operation(summary = "获得MQTT配置分页")
    @PreAuthorize("@ss.hasPermission('mqtt:config:query')")
    public CommonResult<PageResult<ConfigRespVO>> getConfigPage(@Valid ConfigPageReqVO pageReqVO) {
        PageResult<MqttConfigDO> pageResult = mqttConfigService.getConfigPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, ConfigRespVO.class));
    }

    @PostMapping("/create")
    @Operation(summary = "创建MQTT配置")
    @PreAuthorize("@ss.hasPermission('mqtt:config:create')")
    public CommonResult<Long> createConfig(@Valid @RequestBody MqttConfigDO config) {
        Long configId = mqttConfigService.createConfig(config);
        return success(configId);
    }

    @PutMapping("/update")
    @Operation(summary = "更新MQTT配置")
    @PreAuthorize("@ss.hasPermission('mqtt:config:update')")
    public CommonResult<Boolean> updateConfig(@Valid @RequestBody MqttConfigDO config) {
        mqttConfigService.updateConfig(config);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除MQTT配置")
    @Parameter(name = "id", description = "配置ID", required = true)
    @PreAuthorize("@ss.hasPermission('mqtt:config:delete')")
    public CommonResult<Boolean> deleteConfig(@RequestParam("id") Long id) {
        mqttConfigService.deleteConfig(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获取MQTT配置")
    @Parameter(name = "id", description = "配置ID", required = true)
    @PreAuthorize("@ss.hasPermission('mqtt:config:query')")
    public CommonResult<MqttConfigDO> getConfig(@RequestParam("id") Long id) {
        MqttConfigDO config = mqttConfigService.getConfigById(id);
        return success(config);
    }

    @GetMapping("/list")
    @Operation(summary = "获取启用的MQTT配置列表")
    @PreAuthorize("@ss.hasPermission('mqtt:config:query')")
    public CommonResult<List<MqttConfigDO>> getEnabledConfigs() {
        List<MqttConfigDO> configs = mqttConfigService.getEnabledConfigs();
        return success(configs);
    }

    @PostMapping("/start")
    @Operation(summary = "启动MQTT实例")
    @Parameter(name = "id", description = "配置ID", required = true)
    @PreAuthorize("@ss.hasPermission('mqtt:config:manage')")
    public CommonResult<Boolean> startInstance(@RequestParam("id") Long id) {
        mqttConfigService.startInstance(id);
        return success(true);
    }

    @PostMapping("/stop")
    @Operation(summary = "停止MQTT实例")
    @Parameter(name = "id", description = "配置ID", required = true)
    @PreAuthorize("@ss.hasPermission('mqtt:config:manage')")
    public CommonResult<Boolean> stopInstance(@RequestParam("id") Long id) {
        mqttConfigService.stopInstance(id);
        return success(true);
    }

    @GetMapping("/status")
    @Operation(summary = "获取MQTT实例状态")
    @Parameter(name = "id", description = "配置ID", required = true)
    @PreAuthorize("@ss.hasPermission('mqtt:config:query')")
    public CommonResult<Boolean> getInstanceStatus(@RequestParam("id") Long id) {
        boolean isRunning = mqttConfigService.isInstanceRunning(id);
        return success(isRunning);
    }

    @PostMapping("/init")
    @Operation(summary = "初始化所有启用的MQTT实例")
    @PreAuthorize("@ss.hasPermission('mqtt:config:manage')")
    public CommonResult<Boolean> initAllInstances() {
        mqttConfigService.initAllEnabledInstances();
        return success(true);
    }

    @PostMapping("/reconnect")
    @Operation(summary = "手动重连MQTT实例")
    @Parameter(name = "id", description = "配置ID", required = true)
    @PreAuthorize("@ss.hasPermission('mqtt:config:manage')")
    public CommonResult<Boolean> reconnectInstance(@RequestParam("id") Long id) {
        mqttInstanceManager.reconnectInstance(id);
        return success(true);
    }

    @GetMapping("/connection-status")
    @Operation(summary = "获取MQTT实例连接状态")
    @Parameter(name = "id", description = "配置ID", required = true)
    @PreAuthorize("@ss.hasPermission('mqtt:config:query')")
    public CommonResult<Boolean> getConnectionStatus(@RequestParam("id") Long id) {
        boolean isConnected = mqttInstanceManager.isInstanceConnected(id);
        return success(isConnected);
    }

    @GetMapping("/reconnecting-status")
    @Operation(summary = "获取MQTT实例重连状态")
    @Parameter(name = "id", description = "配置ID", required = true)
    @PreAuthorize("@ss.hasPermission('mqtt:config:query')")
    public CommonResult<Boolean> getReconnectingStatus(@RequestParam("id") Long id) {
        boolean isReconnecting = mqttInstanceManager.isReconnecting(id);
        return success(isReconnecting);
    }

    @PostMapping("/check-connections")
    @Operation(summary = "手动检查所有MQTT连接状态")
    @PreAuthorize("@ss.hasPermission('mqtt:config:manage')")
    public CommonResult<String> checkConnections() {
        mqttConnectionMonitorService.manualCheckConnection();
        return success("连接状态检查已触发");
    }

    @GetMapping("/connection-report")
    @Operation(summary = "获取MQTT连接状态报告")
    @PreAuthorize("@ss.hasPermission('mqtt:config:query')")
    public CommonResult<String> getConnectionReport() {
        String report = mqttConnectionMonitorService.getConnectionStatusReport();
        return success(report);
    }

    @PostMapping("/ping")
    @Operation(summary = "主动PING MQTT客户端")
    @Parameter(name = "id", description = "配置ID", required = true)
    @PreAuthorize("@ss.hasPermission('mqtt:config:query')")
    public CommonResult<Boolean> pingClient(@RequestParam("id") Long id) {
        boolean result = mqttInstanceManager.pingClient(id);
        return success(result);
    }

    @PostMapping("/validate-outbound")
    @Operation(summary = "验证出站处理器状态")
    @Parameter(name = "id", description = "配置ID", required = true)
    @PreAuthorize("@ss.hasPermission('mqtt:config:query')")
    public CommonResult<Boolean> validateOutboundHandler(@RequestParam("id") Long id) {
        boolean isValid = mqttInstanceManager.validateOutboundHandler(id);
        return success(isValid);
    }

//    @PostMapping("/test-disconnection")
//    @Operation(summary = "测试连接断开记录")
//    @Parameter(name = "clientId", description = "客户端ID", required = true)
//    @Parameter(name = "reason", description = "断开原因", required = false)
//    @PreAuthorize("@ss.hasPermission('mqtt:config:manage')")
//    public CommonResult<String> testDisconnection(@RequestParam("clientId") String clientId,
//                                                @RequestParam(value = "reason", required = false) String reason) {
//        try {
//            mqttConnectionListener.manualRecordDisconnection(clientId, reason != null ? reason : "测试断开");
//            return success("连接断开记录测试完成");
//        } catch (Exception e) {
//            log.error("测试连接断开记录失败", e);
//            return success("测试失败: " + e.getMessage());
//        }
//    }
} 